import util from './util';
let wxUserInfor = function (callback) {
  function queryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
  }
  var firstCode = true
  this.getCode = function () {
    var code = queryString('code');
    var format = 'json';
    if (firstCode && code) {
      $.ajax({
        url: 'http://match.lottery.sina.com.cn/activity/zfc_activity/wxAuthCallback?code=' + code + '&format=' + format,
        dataType: 'jsonp',
        data: {},
        cache: false,
        jsonpCallback: 'wxAuthCallback',
        type: 'get',
        success: function (data) {
          var result = data.result;
          var rcode = result.status.code;
          firstCode = false;
          if (rcode === 0) {
            var rdata = result.data;
            util.storage.setItem(util._zfcUsr, JSON.stringify(rdata));
            // setInfo(rdata);
            callback && callback(rdata);
          } else {
            var rdata = util.storage.getItem(util._zfcUsr);
            if (rdata) {
              rdata = JSON.parse(rdata);
              // setInfo(rdata);
              callback && callback(rdata);
            } else {
              console.log('微信授权失败')
            }
          }
        }
      });
    } else {
      var rdata = util.storage.getItem(util._zfcUsr);
      if (rdata) {
        rdata = JSON.parse(rdata);
        // setInfo(rdata);
        callback && callback(rdata);
      } else {
        console.log('微信授权失败')
      }
    }
  };
  this.init = function () {
    this.getCode()
  };
  this.init();
  function setInfo(data) {
    util.storage.setItem("usrName",data.nickname)
    util.storage.setItem("usrPhoto",data.headimgurl)
    util.storage.setItem("openId",data.openid)
    util.storage.setItem("usrSex",data.sex)
  }
  return this;
};
export default wxUserInfor